#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>

#define MAXLINE         4096
#define SA      struct sockaddr

int main(int argc, char** argv) {
	int socketfd,n;
	char recvline[MAXLINE+1];
	struct sockaddr_in servaddr;
	char buff[MAXLINE];
	//struct pollfd* clientfd[1];
	
	if (argc != 2) {
		printf("usage: ./daytimeclient <IPAddress>\n");
		exit(1);
	}
	// Create an Internet socket descriptor for TCP connection
	if ((socketfd=socket(AF_INET,SOCK_STREAM,0)) < 0) {
		perror("Socket error");
		exit(1);
	}
	
	// Initialize the structure containing the server to connect to
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(1111);
	if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <=0 ) {
		printf("inet_pton error for %s\n",argv[1]);
		exit(1);
	}

	// Make connection to the server
	if (connect(socketfd, (SA *) &servaddr, sizeof(servaddr)) < 0) {
		perror("Connect error");
		exit(1);
	}
	
	while(1) {
		scanf("%s",buff);
		if(strcmp(buff,"exit")==0)
			exit(0);
		write(socketfd,buff,MAXLINE);
		// Read information from the server and display it
	//	if(poll(
		while(n=read(socketfd, recvline, MAXLINE) >0)
		{	recvline[n]="\0";
			printf("%s \n",recvline);
	/*	if (fputs(recvline,stdout) == EOF) {
			printf("fputs error\n");
			exit(1);
		}
	*/
		}
	}
	close(socketfd);
	return 0;
}
		